<!--
  按照需求自行定义暴露的prop
-->
<template>
  <view class="roc-navbar">
    <u-navbar
      :safeAreaInsetTop="true"
      :fixed="true"
      :border="false"
      height="44px"
      :title="title"
      :titleWidth="titleWidth"
      :bgColor="$u.color['primary']"
      :leftIcon="leftIcon"
      :leftText="leftText"
      leftIconSize="20px"
      leftIconColor="#fff"
      :rightIcon="rightIcon"
      :rightText="rightText"
      rightIconSize="20px"
      rightIconColor="#fff"
      :placeholder="true"
      :titleStyle="{
        color: '#fff',
      }"
      :autoBack="false"
      @leftClick="leftClick"
      @rightClick="rightClick"
    ></u-navbar>
  </view>
</template>

<script>
export default {
  name: 'roc-navbar',
  props: {
    titleWidth: {
      type: String,
      default: '400rpx',
    },
    title: {
      type: String,
      default: '',
    },
    leftText: {
      type: String,
      default: '',
    },
    rightIcon: {
      type: String,
      default: '',
    },
    rightText: {
      type: String,
      default: '',
    },
    autoBack: {
      type: Boolean,
      default: true,
    },
    backIndex: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      pageUrl: '',
      pageNum: 0,
      leftIcon: 'arrow-left',
    }
  },
  created() {
    let pages = getCurrentPages()
    // 获取当前页面，页面栈中的最后一个即为项为当前页面，route属性为页面路径
    this.pageUrl = pages[pages.length - 1] && pages[pages.length - 1].route
    this.pageNum = pages.length
  },
  watch: {
    autoBack: {
      handler(val) {
        if (val) {
          this.leftIcon = 'arrow-left'
        } else {
          this.leftIcon = ' '
        }
      },
      immediate: true,
    },
  },
  methods: {
    leftClick() {
      // 返回时候只有当前页面了，返回到首页
      if (this.autoBack) {
        if (this.pageNum == 1) {
          uni
            .switchTab({
              url: '/pages/index/index',
            })
            .catch(() => {
              uni.reLaunch({
                url: '/pages/index/index',
              })
            })
        } else {
          uni.navigateBack({ delta: this.backIndex })
        }
      }
      this.$emit('leftClick')
    },
    rightClick() {
      this.$emit('rightClick')
    },
    getPath(path) {
      return path ? path.split('?').shift() : path
    },
  },
}
</script>

<style lang="scss" scoped></style>
